﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace C12_Ex03_Shaked_032675316_Itay_032511057
{
    public class AsyncFaceBookGalleriesDownloadHandler : IFaceBookGalleriesDownloadHandler
    {
        private static IFaceBookGalleriesDownloadHandler m_Instance;

        private AsyncFaceBookGalleriesDownloadHandler()
        {
        }

        protected class DownloadImageInfo
        {
            public string Photo { get; set; }

            public string AlbumName { get; set; }

            public string DownloadFolder { get; set; }
        }

        private static void DownloadImageThreadPoolCallback(object i_DownloadImageInfo)
        {
            DownloadImageInfo downloadImageInfo = (DownloadImageInfo)i_DownloadImageInfo;
            IFaceBookGalleriesDownloadHandler downloadHandlerInstance = FaceBookGalleriesDownloadHandler.Instance;
            downloadHandlerInstance.DownloadImage(downloadImageInfo.Photo, downloadImageInfo.AlbumName, downloadImageInfo.DownloadFolder);
        }

        public static IFaceBookGalleriesDownloadHandler Instance
        {
            get 
            {
                if (m_Instance == null)
                {
                    m_Instance = new AsyncFaceBookGalleriesDownloadHandler();
                }

                return m_Instance;
            }
        }

        public void DownloadImage(string i_Photo, string i_AlbumName, string i_DownloadFolder)
        {
            string filenameFromUrl = i_Photo.Split('/').Last();
            string directoryPath = i_DownloadFolder + Path.DirectorySeparatorChar + i_AlbumName;
            string fileFullPath = directoryPath + Path.DirectorySeparatorChar + filenameFromUrl;

            DownloadImageInfo downloadImageInfo = new DownloadImageInfo() { Photo = i_Photo, AlbumName = i_AlbumName, DownloadFolder = i_DownloadFolder };
            ThreadPool.QueueUserWorkItem(DownloadImageThreadPoolCallback, downloadImageInfo);
        }
    }
}
